package com.xinlong.shop.framework.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinlong.shop.framework.core.entity.SysAdmin;
import com.xinlong.shop.framework.core.mapper.SysAdminMapper;
import com.xinlong.shop.framework.security.util.TokenUtil;
import com.xinlong.shop.framework.service.ISysAdminService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @Author Sylow
 * @Description
 * @Date: Created in 01:28 2022/5/25
 */
@Service
public class SysAdminServiceImpl extends ServiceImpl<SysAdminMapper, SysAdmin> implements ISysAdminService {


    private final UserDetailsServiceImpl userDetailsServiceImpl;

    private final TokenUtil tokenUtil;

    private final PasswordEncoder passwordEncoder;

    private final SysAdminMapper sysAdminMapper;


    private static final Logger logger = LoggerFactory.getLogger(SysAdminServiceImpl.class);

    public SysAdminServiceImpl(@Lazy UserDetailsServiceImpl userDetailsServiceImpl, TokenUtil tokenUtil, PasswordEncoder passwordEncoder, SysAdminMapper sysAdminMapper) {
        this.userDetailsServiceImpl = userDetailsServiceImpl;
        this.tokenUtil = tokenUtil;
        this.passwordEncoder = passwordEncoder;
        this.sysAdminMapper = sysAdminMapper;
    }

    @Override
    public String login(String userName, String password) {
        String token = null;
        try {
            UserDetails userDetails = userDetailsServiceImpl.loadUserByUsername(userName);
            if (!passwordEncoder.matches(password, userDetails.getPassword())) {
                throw new BadCredentialsException("密码不正确");
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = tokenUtil.generateToken(userDetails, false);
        } catch (AuthenticationException e) {
            logger.warn("登录异常:{}", e.getMessage());
        }
        return token;
    }

    @Override
    public SysAdmin findByUserName(String userName) {

        return this.sysAdminMapper.getByUserName(userName);
    }

    @Override
    public void setUserInfo(SysAdmin sysAdmin) {
        UpdateWrapper<SysAdmin> sysUserUpdateWrapper = new UpdateWrapper<>();
        sysUserUpdateWrapper.eq("id", sysAdmin.getId());
        sysUserUpdateWrapper.set("nick_name", sysAdmin.getNickName());
        sysUserUpdateWrapper.set("full_name", sysAdmin.getFullName());
        sysUserUpdateWrapper.set("mobile", sysAdmin.getMobile());
        sysUserUpdateWrapper.set("email", sysAdmin.getEmail());
        this.update(null, sysUserUpdateWrapper);
    }

    @Override
    public void update(SysAdmin sysAdmin, Integer id) {
        UpdateWrapper<SysAdmin> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        String password = sysAdmin.getPassword();
        if (StrUtil.isNotBlank(password)) {
            password = new BCryptPasswordEncoder().encode(password);
            sysAdmin.setPassword(password);
        } else {
            // 空字符串密码不更新
            sysAdmin.setPassword(null);
        }

        this.update(sysAdmin, updateWrapper);
    }

    @Override
    public void delete(Integer id) {
        UpdateWrapper<SysAdmin> deleteWrapper = new UpdateWrapper<>();
        deleteWrapper.eq("id", id);
        this.remove(deleteWrapper);
    }

    @Override
    public String generateRefreshToken(String userName, boolean refreshToken) {
        UserDetails userDetails = userDetailsServiceImpl.loadUserByUsername(userName);
        String token = tokenUtil.generateToken(userDetails, refreshToken);
        return token;
    }

//    @Override
//    public String refreshToken(String userName, String refreshToken) {
//        UserDetails userDetails = userDetailsServiceImpl.loadUserByUsername(userName);
//        // 验证token是否有效
//        if(tokenUtil.validateToken(refreshToken, userDetails)) {
//            String token = tokenUtil.generateToken(userDetails, false);
//            return token;
//        }
//        return "";
//    }

}
